package com.api.shihua.action;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.shihua.util.BaseUtil;
import com.api.shihua.util.LogTool;
import weaver.conn.RecordSet;
import weaver.general.Util;

import java.text.SimpleDateFormat;
import java.util.*;

/*
    变更数据公共类
    校验导入数据 的真实性   不能越过权限变更  所以需要校验  数据


 */
public class ChangeBaseAction {
    private final static LogTool log = new LogTool("/log/zjl/",false);
    public JSONObject FBjsons=new JSONObject();//分部数据
    public JSONObject DetailJson=new JSONObject();//建模明细数据
    public JSONObject CheckDatajson=new JSONObject();//保存校验数据
    public JSONObject sqlData=new JSONObject();//保存校验数据
    public JSONObject level_1json=new JSONObject();//一级分解对应的 分部金额金额汇总数据
    public JSONObject level_3json=new JSONObject();//一级分解对应的 部门金额金额汇总数据
    public JSONObject level_2json=new JSONObject();//二级分解对应的 部门金额汇总数据 添加部门对应分部
    public JSONObject fbdpje_json=new JSONObject();//分部大盘金额
    public JSONObject bmdpje_json=new JSONObject();//部门大盘金额

    public String level1updid="";//保存一级分类的待更新大盘金额的 的 数据的id
    public String level1updDelteid="";//保存一级分类的待更新作废的 数据的id
    public String level2updDelteid="";//保存二级分类的待更新作废的 数据的id

    public JSONObject bmbz=new JSONObject();//记录部门备注
    public JSONObject bmje=new JSONObject();//记录部门金额
    public List<Map<String, Object>> listMap=new ArrayList<Map<String, Object>>();//直接更新的 sql 语句集合
    public List<Object> Enterylist=new ArrayList<Object>();//一级模型数据
    public List<Object> leve2Enterylist=new ArrayList<Object>();//二级模型数据
    public JSONObject bmreq=new JSONObject();//部门映射的 requestid
    public SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public String currentDate=sim.format(new Date()).split(" ")[0];
    public String currentTime=sim.format(new Date()).split(" ")[1];

    /*
     requestid:变更流程ID
     Modeljson:单位对应的建模数据  原始数据变更之前的
     */
    public String checkDate(String requestid,JSONObject Modeljson,String formid,String bgwfmainrequestid) {
        RecordSet re = new RecordSet();
        //单位  个人  大盘 分解
        //sffjzcjcshgr:分解类型
        //hrfbdp:划入分部大盘
        //bjldw:被奖励单位
        //bjlbm:被奖励部门
        //ry:人员
        //bz:备注
        //je:金额
        //modelid:modelid
        try {
            String sql = "select a.requestid,b.*,c.departmentid,c.subcompanyid1,d.subcompanyid1 depsubid from formtable_main_" + formid + " a,formtable_main_" + formid + "_dt2 b left join hrmresource c on b.ry=c,id left join hrmdepartment d on b.bjlbm=d.id  where a.id=b.mainid and a.requestid='" + requestid + "'";
            log.writeLog("frist_detail--->"+sql);
            re.execute(sql);
            while (re.next()) {
                JSONObject reJson=new JSONObject();
                String modelid = Util.null2String(re.getString("modelid")).trim();
                String bgrequestid= Util.null2String(re.getString("requestid")).trim();
                String sffjzcjcshgr = Util.null2String(re.getString("sffjzcjcshgr")).trim();
                if(!"0".equals(sffjzcjcshgr)&&!"1".equals(sffjzcjcshgr)&&!"2".equals(sffjzcjcshgr)){
                    throw  new Exception(modelid+"变更分解类型有误");
                }

                String hrfbdp = Util.null2String(re.getString("hrfbdp")).trim();
                String bjldw = Util.null2String(re.getString("bjldw")).trim();
                String bjlbm = Util.null2String(re.getString("bjlbm")).trim();
                String departmentid = Util.null2String(re.getString("departmentid")).trim();//人员部门
                String subcompanyid1 = Util.null2String(re.getString("subcompanyid1")).trim();//人员分部
                String depsubid = Util.null2String(re.getString("depsubid")).trim();//部门分部

                String ry = Util.null2String(re.getString("ry")).trim();
                String bz = Util.null2String(re.getString("bz")).trim();
                String je = Util.null2String(re.getString("je")).trim();
                //大盘分级 金额必须 控制
                if(!("2".equals(sffjzcjcshgr)&&Util.getDoubleValue(hrfbdp,0)>0&&Util.getDoubleValue(je,0)==0)){
                    throw  new Exception(modelid+"大盘分解只能填写大盘分解金额");
                }
                if(("0".equals(sffjzcjcshgr)||"2".equals(sffjzcjcshgr))&&!"".equals(depsubid)){//单位
                    //bjldw=depsubid;
                    if("".equals(bjldw)){
                        bjldw=depsubid;
                    }
                }
                if("1".equals(sffjzcjcshgr)&&!"".equals(subcompanyid1)&&!"".equals(departmentid)){//人员

                    if("".equals(bjldw)){
                        bjldw=subcompanyid1;
                    }
                    bjlbm=departmentid;
                }

                //判断分部权限以及  数据权限
                if(this.FBjsons.getJSONObject(bjldw)==null||this.FBjsons.getJSONObject(bjldw).size()<=0){
                    throw  new Exception("您没有此分部ID的变更权限:"+BaseUtil.getSubNameBySubid(bjldw) );
                }

                reJson.put("sffjzcjcshgr",sffjzcjcshgr);
                reJson.put("hrfbdp",hrfbdp);
                reJson.put("bgrequestid",bgrequestid);
                reJson.put("bjldw",bjldw);
                reJson.put("bjlbm",bjlbm);
                reJson.put("ry",ry);
                reJson.put("bz",bz);
                reJson.put("je",je);
                reJson.put("modelid",modelid);
                if("0".equals(sffjzcjcshgr)){
                    bmbz.put(bjlbm+"",bz);//奖励单位部门备注  用于二级级分解  备注
                    bmje.put(bjlbm+"",je+"");//奖励单位部门金额  用于二级级分解  金额
                }

                setLevel_1json(bjldw,je);//设置分部金额合并
                setLevel_3json(bjlbm,je);//设置部门金额合并
                if("2".equals(sffjzcjcshgr)){
                    setFbpd(bjldw,hrfbdp);//设置分部大盘汇总
                }else{
                    setFbpd(bjldw,je);//设置分部大盘汇总
                }

                if ("".equals(modelid)) {//新增
                    setsqlData_level1(reJson);
                }else{//修改
                    level1updDelteid=level1updDelteid+modelid+",";
                    JSONObject SingDetailJson=DetailJson.getJSONObject(modelid);
                    if(SingDetailJson==null||SingDetailJson.size()<=0){
                        throw  new Exception(modelid+"为获取单条明细数据");
                    }
                    String yfjlx=Util.null2String( SingDetailJson.getString("fjlx")).trim();//原分解类型
                    if(!"0".equals(yfjlx)&&!"1".equals(yfjlx)&&!"2".equals(yfjlx)){
                        throw  new Exception(modelid+"分解类型有误");
                    }
                    //个人转 单位   清空 人员 人员金额 以及备注   修改 部门，部门金额 部门备注    分部加上 主流程ID来更新分部大盘金额
                    if("0".equals(sffjzcjcshgr)&&"1".equals(yfjlx)){
                      Map<String,Object> map=new  HashMap<String,Object>();
                      String updsql="update uf_zjljlhzbb set xm=?,grjlje=?,grjlbz=?,jldwbm=?,dwjljebm=?,dwjlbz=?,mess=?  where id='"+modelid+"' ";
                      Object[] objects=new Object[7];
                      objects[0]=-1;
                      objects[1]=0;
                      objects[2]="";
                      objects[3]=Util.getIntValue(bjlbm,-1);
                      objects[4]=Util.getDoubleValue(je,0);
                      objects[5]=bz;
                      objects[6]="个人转单位";
                      map.put("sql",updsql);
                      map.put("params",objects);
                      listMap.add(map);
                        level1updid=level1updid+modelid+",";
                    }
                    //个人转 大盘  清空 人员 人员金额 以及备注    部门，部门金额 部门备注  修改金额
                    if("2".equals(sffjzcjcshgr)&&"1".equals(yfjlx)) {
                        Map<String, Object> map = new HashMap<String, Object>();
                        String updsql = "update uf_zjljlhzbb set xm=?,grjlje=?,grjlbz=?,jldwbm=?,dwjljebm=?,dwjlbz=?,hrfbdpje=?,mess=?  where id='" + modelid + "' ";
                        Object[] objects = new Object[8];
                        objects[0] = -1;
                        objects[1] = 0;
                        objects[2] = "";
                        objects[3] = -1;
                        objects[4] = 0;
                        objects[5] = "";
                        objects[6] = Util.getDoubleValue(je, 0);
                        objects[7] = "个人转大盘";
                        map.put("sql", updsql);
                        map.put("params", objects);
                        listMap.add(map);
                    }
                    //单位转个人
                    if("0".equals(yfjlx)&&"1".equals(sffjzcjcshgr)){
                        Map<String,Object> map=new  HashMap<String,Object>();
                        String updsql="update uf_zjljlhzbb set xm=?,grjlje=?,grjlbz=?,jldwbm=?,dwjljebm=?,dwjlbz=?,mess=?  where id='"+modelid+"' ";
                        Object[] objects=new Object[7];
                        objects[0]=Util.getIntValue(ry,-1);
                        objects[1]=Util.getDoubleValue(je,0);
                        objects[2]=bz;
                        objects[3]=-1;
                        objects[4]=0;
                        objects[5]="";
                        objects[6]="个人转单位";
                        map.put("sql",updsql);
                        map.put("params",objects);
                        listMap.add(map);
                        level1updid=level1updid+modelid+",";
                    }
                    //单位转大盘
                    if("2".equals(sffjzcjcshgr)&&"0".equals(yfjlx)) {
                        Map<String, Object> map = new HashMap<String, Object>();
                        String updsql = "update uf_zjljlhzbb set xm=?,grjlje=?,grjlbz=?,jldwbm=?,dwjljebm=?,dwjlbz=?,hrfbdpje=?,mess=?  where id='" + modelid + "' ";
                        Object[] objects = new Object[8];
                        objects[0] = -1;
                        objects[1] = 0;
                        objects[2] = "";
                        objects[3] = -1;
                        objects[4] = 0;
                        objects[5] = "";
                        objects[6] = Util.getDoubleValue(je, 0);
                        objects[7] = "单位转大盘";
                        map.put("sql", updsql);
                        map.put("params", objects);
                        listMap.add(map);
                    }
                    //大盘转个人  金额不能为空或者0
                    if("1".equals(sffjzcjcshgr)&&"2".equals(yfjlx)) {
                        if(je==null||Util.getDoubleValue(je)<=0){
                            throw  new Exception("大盘转给个人金额不能为空或小于等于0:"+BaseUtil.getSubNameBySubid(bjldw) );
                        }
                        Map<String, Object> map = new HashMap<String, Object>();
                        String updsql = "update uf_zjljlhzbb set xm=?,grjlje=?,grjlbz=?,mess=?  where id='" + modelid + "' ";
                        Object[] objects = new Object[4];
                        objects[0]=Util.getIntValue(ry,-1);
                        objects[1]=Util.getDoubleValue(je,0);
                        objects[2] = bz;
                        objects[3] = "大盘转个人";
                        map.put("sql", updsql);
                        map.put("params", objects);
                        listMap.add(map);
                        level1updid=level1updid+modelid+",";
                    }
                    //大盘转单位 金额不能为空或者0
                    if("0".equals(sffjzcjcshgr)&&"2".equals(yfjlx)) {
                        if(je==null||Util.getDoubleValue(je)<=0){
                            throw  new Exception("大盘转给单位金额不能为空或小于等于0:"+BaseUtil.getSubNameBySubid(bjldw) );
                        }
                        Map<String, Object> map = new HashMap<String, Object>();
                        String updsql = "update uf_zjljlhzbb set jldwbm=?,dwjljebm=?,dwjlbz=?,mess=?  where id='" + modelid + "' ";
                        Object[] objects = new Object[4];
                        objects[0]=Util.getIntValue(bjlbm,-1);
                        objects[1]=Util.getDoubleValue(je,0);
                        objects[2] = bz;
                        objects[3] = "大盘转单位";
                        map.put("sql", updsql);
                        map.put("params", objects);
                        listMap.add(map);
                        level1updid=level1updid+modelid+",";
                    }

                }
            }
            //个人分解明细
            RecordSet re_dt2=new RecordSet();
            String sql_dt2="select a.requestid,b.* from formtable_main_" + formid + " a,formtable_main_" + formid + "_dt3 b  where a.id=b.mainid and a.requestid='" + requestid + "'";
            re_dt2.execute(sql_dt2);
            while(re_dt2.next()){
                String bgrequestid= Util.null2String(re.getString("requestid")).trim();
                String bjldw=Util.null2String(re_dt2.getString("bjldw")).trim() ;//被奖励单位
                String bjlbm=Util.null2String(re_dt2.getString("bjlbm")).trim() ;//被奖励部门
                String ry=Util.null2String(re_dt2.getString("ry")).trim() ;//人员
                String je=Util.null2String(re_dt2.getString("je")).trim() ;//金额
                String hrbmdp=Util.null2String(re_dt2.getString("hrbmdp")).trim() ;//划入部门大盘
                String bz=Util.null2String(re_dt2.getString("bz")).trim() ;//备注
                String modelid=Util.null2String(re_dt2.getString("modelid")).trim() ;//modelid
                JSONObject reJson=new JSONObject();
                reJson.put("bgrequestid",bgrequestid);
                reJson.put("bjldw",bjldw);
                reJson.put("bjlbm",bjlbm);
                reJson.put("ry",ry);
                reJson.put("je",je);
                reJson.put("hrbmdp",hrbmdp);
                reJson.put("bz",bz);
                reJson.put("modelid",modelid);
                setLevel_2json(bjlbm,je);//设置部门金额火鬃
                setBmpd(bjlbm,hrbmdp);//设置部门大盘汇总
                //设置数据
                if ("".equals(modelid)) {//新增
                    setsqlData_level2(reJson);
                }else {//修改
                    level2updDelteid=level2updDelteid+modelid+",";
                    Map<String, Object> map = new HashMap<String, Object>();
                    String updsql = "update uf_zjljlhzbb set xm=?,grjlje=?,grjlbz=?,mess=?  where id='" + modelid + "' ";
                    Object[] objects = new Object[4];
                    objects[0]=Util.getIntValue(ry,-1);
                    objects[1]=Util.getDoubleValue(je,0);
                    objects[2] = bz;
                    objects[3] = "个人修改";
                    map.put("sql", updsql);
                    map.put("params", objects);
                    listMap.add(map);
                }

            }
            //数据校验开始   分部=单位+分部大盘   部门=个人+部门大盘
            try {
                Set<String> fbKey = this.FBjsons.keySet();
                for (String key : fbKey) {
                    double fbje = 0;
                    JSONObject fristJson = this.FBjsons.getJSONObject(key).getJSONArray("0").getJSONObject(0);
                    fbje = Util.getDoubleValue(fristJson.getString("jljefb"));
                    //一级获取分部金额
                    double modelfbje=Util.getDoubleValue(level_1json.getString(key),0);
                    double modelfbdpje=Util.getDoubleValue(fbdpje_json.getString(key),0);;//分部大盘
                    if(fbje!=(modelfbje+modelfbdpje)){
                        throw  new Exception(BaseUtil.getSubNameBySubid(key)+"一级分解金额不一致:单位金额"+fbje+" 分解金额"+(modelfbje+modelfbdpje));
                    }
                }
                if(level_3json!=null&&level_3json.size()>0){
                    Set<String> bmkey=level_3json.keySet();
                    for(String key:bmkey){
                        double level1bmje = 0;Util.getDoubleValue(level_3json.getString(key));
                        //获取二级金额 一级大盘
                        double modelbmje=Util.getDoubleValue(level_2json.getString(key),0);
                        double modelbmdpje=Util.getDoubleValue(bmdpje_json.getString(key),0);;//部门大盘
                        if(level1bmje!=(modelbmje+modelbmdpje)){
                            throw  new Exception(BaseUtil.getSubByDep(key)+"二级分解金额不一致:科室单位金额"+level1bmje+" 分解金额"+(modelbmje+modelbmdpje));
                        }
                    }
                }
            //设置一级分部大盘金额 以及 新增数据的大盘金额
                if(fbdpje_json!=null&&fbdpje_json.size()>0){
                    if(level1updid.endsWith(",")){
                        level1updid=level1updid.substring(0,level1updid.length()-1);
                    }
                    Set<String> fbkey=fbdpje_json.keySet();
                    Map<String, Object> map =null;// new HashMap<String, Object>();
                    for(String key:fbkey){
                        map =new HashMap<String, Object>();
                        BaseUtil.getAdd(fbdpje_json.getString(key),"0",2);
                        double udpje=Util.getDoubleValue(fbdpje_json.getString(key),0);
                        Object[] objects = new Object[1];
                        objects[0]=udpje;
                        map.put("sql", "update uf_zjljlhzbb set hrfbdpje=? where mainrequestid='"+bgwfmainrequestid+"' and " +
                                " isnull(sfyx,-1) in (0,-1) and id in ("+level1updid+")");
                        map.put("params", objects);
                        listMap.add(map);
                    }


                }
            //设置二级部门大盘金额  以及新增说数据的大盘金额
                if(bmdpje_json!=null&&bmdpje_json.size()>0){

                    Set<String> fbkey=bmdpje_json.keySet();
                    Map<String, Object> map =null;// new HashMap<String, Object>();
                    for(String key:fbkey){
                        map =new HashMap<String, Object>();
                        BaseUtil.getAdd(bmdpje_json.getString(key),"0",2);
                        double udpje=Util.getDoubleValue(bmdpje_json.getString(key),0);
                        Object[] objects = new Object[1];
                        objects[0]=udpje;
                        map.put("sql", "update uf_zjljlhzbb set hrfbdpje=? where mainrequestid='"+bgwfmainrequestid+"' and " +
                                " isnull(sfyx,-1) in (0,-1) ");
                        map.put("params", objects);
                        listMap.add(map);
                    }


                }

            }catch(Exception e1){
                throw  new Exception("金额校验异常!"+ e1.getMessage());
            }


        }catch(Exception e){
            return "校验异常"+e.getMessage();
        }
            return "";

    }
    //设置 一级分解对应的 分部金额汇总数据  level_1json
    public void setLevel_1json(String fb,String je){
        if(fb==null||"".equals(Util.null2String(fb).trim())){
            return;
        }
        if(level_1json==null){
                level_1json=new JSONObject();
        }

        String jsonje=Util.null2String(level_1json.getString(fb)).trim() ;
        jsonje=BaseUtil.getAdd(jsonje,je,2);
        level_1json.put(fb,jsonje);
    }
    //设置 一级分解对应的 分部金额汇总数据  level_1json
    public void setLevel_3json(String bm,String je){
        if(bm==null||"".equals(Util.null2String(bm).trim())){
            return;
        }
        if(level_3json==null){
            level_3json=new JSONObject();
        }

        String jsonje=Util.null2String(level_3json.getString(bm)).trim() ;
        jsonje=BaseUtil.getAdd(jsonje,je,2);
        level_3json.put(bm,jsonje);
    }
    //设置 一级分解对应的 分部金额汇总数据  level_1json
    public void setLevel_1json_bak(String fb,String bm,String je){
        if(bm==null||fb==null||"".equals(Util.null2String(fb).trim())){
            return;
        }
        if(level_1json==null){
            level_1json=new JSONObject();
        }
        JSONObject fbJson=level_1json.getJSONObject(fb);
        if(fbJson==null){
            fbJson=new JSONObject();
            level_1json.put(fb,fbJson);
        }
        String jsonje=Util.null2String(fbJson.getString(fb)).trim() ;
        jsonje=BaseUtil.getAdd(jsonje,je,2);
        fbJson.put(fb,jsonje);
    }

    //设置 二级分解对应的 部门金额汇总数据  leve2_1json
    public void setLevel_2json(String bm,String je){
        if(bm==null||"".equals(Util.null2String(bm).trim())){
            return;
        }
        if(level_2json==null){
            level_2json=new JSONObject();
        }
        String jsonje=level_2json.getString(bm);
        jsonje=BaseUtil.getAdd(jsonje,je,2);
        level_2json.put(bm,jsonje);
    }
    //设置 分部大盘金额
    public void setFbpd(String fb,String je)throws Exception{
        if(fbdpje_json==null){
            fbdpje_json=new JSONObject();
        }
        if(fb==null||"".equals(Util.null2String(fb).trim())){
            return;
        }
        String demodp=fbdpje_json.getString(fb);
        if(Util.getDoubleValue(demodp,0)>0&&Util.getDoubleValue(je,0)>0&&Util.getDoubleValue(je,0)!=Util.getDoubleValue(demodp,0)){
                throw  new Exception("分部大盘金额必须一致!");
        }else{
            demodp=BaseUtil.getAdd(demodp,je,2);
            fbdpje_json.put(fb,demodp);
        }
    }
    //设置 部门大盘金额
    public void setBmpd(String bm,String je)throws Exception{
        if(fbdpje_json==null){
            fbdpje_json=new JSONObject();
        }
        if(bm==null||"".equals(Util.null2String(bm).trim())){
            return;
        }
        String demodp=bmdpje_json.getString(bm);
        if(Util.getDoubleValue(demodp,0)>0&&Util.getDoubleValue(je,0)>0&&Util.getDoubleValue(je,0)!=Util.getDoubleValue(demodp,0)){
            throw  new Exception("部门大盘金额必须一致!");
        }else{
            demodp=BaseUtil.getAdd(demodp,je,2);
            bmdpje_json.put(bm,demodp);
        }
    }
    //设置 部门映射 requestid
    public void setBmreq(String bm,String req)throws Exception{
        if(fbdpje_json==null){
            fbdpje_json=new JSONObject();
        }
        if(bm==null||"".equals(Util.null2String(bm).trim())){
            return;
        }
        String reqStr=bmreq.getString(bm);
        if("".equals(Util.null2String(reqStr))){
            throw  new Exception("部门不可重复!");
        }else{
            bmreq.put(bm,reqStr);
        }
    }
   public void setsqlData_level1(JSONObject json)throws Exception{

   }
    public void setsqlData_level2(JSONObject json)throws Exception{

    }
    public JSONObject getBmFristJSON(String bm){

            JSONObject json=new JSONObject();
             if(bm==null||"".equals(Util.null2String(bm).trim())){
                return json;
             }
            String subid=BaseUtil.getSubByDep(bm);
            try{
                JSONObject singleJson= FBjsons.getJSONObject(subid);
                if(singleJson!=null&&singleJson.size()>0){
                    JSONArray jSONArray =singleJson.getJSONArray("1");//一级分解
                    if(jSONArray!=null&&jSONArray.size()>0){
                        for(int i=0;i<jSONArray.size();i++){
                            JSONObject BMJSON= jSONArray.getJSONObject(i);
                            if(BMJSON!=null&&BMJSON.size()>0){
                                String bmStr=BMJSON.getString("jldwbm");
                                if(bm.equals(bmStr)){
                                    return BMJSON;
                                }
                            }
                        }
                    }
                }
            }catch(Exception e){
                log.writeLog("getBmFristJSON--->"+e.getMessage());
            }
            return json;

    }
}
